package com.genius.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.genius.config.MinioConfig;
import com.genius.enums.ResponseType;
import com.genius.exception.GraceException;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class MinioUtils {

    @Autowired
    private MinioConfig prop;

    @Resource
    private MinioClient minioClient;

    /**
     * 文件上传
     *
     * @param file 文件
     * @return Boolean
     */
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (StrUtil.isBlank(originalFilename)){
            throw new RuntimeException();
        }
        String fileName = UUID.fastUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = DateUtil.format(new Date(),"yyyy-MM/dd") + "/" + fileName;
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(prop.getBucketName()).object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            GraceException.display(ResponseType.FILE_UPLOAD_FAILED);
            e.printStackTrace();
            return null;
        }
        return objectName;
    }

    /**
     * 预览图片
     * @param fileName 文件名称
     * @return 文件url
     */
    public String preview(String fileName){
        // 查看文件地址
        GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs.builder()
                .bucket(prop.getBucketName()).
                object(fileName).method(Method.GET).build();
        try {
            return minioClient.getPresignedObjectUrl(build);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件下载
     * @param fileName 文件名称
     * @param res response 响应
     */
    public void download(String fileName, HttpServletResponse res) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(prop.getBucketName())
                .object(fileName).build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)){
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len=response.read(buf))!=-1){
                    os.write(buf,0,len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                // 设置强制下载不打开
                res.setContentType("application/force-download");
                res.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            GraceException.display(ResponseType.FILE_UPLOAD_FAILED);
            e.printStackTrace();
        }
    }

    /**
     * 查看文件对象
     * @return 存储bucket内文件对象信息
     */
    public List<Item> listObjects() {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(prop.getBucketName()).build());
        List<Item> items = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                items.add(result.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return items;
    }

    /**
     * 删除文件
     * @param fileName 文件名称
     * @return 是否删除
     */
    public boolean remove(String fileName){
        try {
            minioClient.removeObject( RemoveObjectArgs.builder().bucket(prop.getBucketName()).object(fileName).build());
        }catch (Exception e){
            return false;
        }
        return true;
    }

    /**
     * 获取待上传文件的预签名URL
     * @param fileName 文件名称
     * @return 上传地址
     */
    public String getUploadUrl(String fileName) {
        String objectName = DateUtil.format(new Date(),"yyyy-MM/dd") + "/" + fileName;
        GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = getGetPresignedObjectUrlArgs(Method.PUT,objectName);
        try {
            return minioClient.getPresignedObjectUrl(getPresignedObjectUrlArgs);
        }catch (Exception e){
            e.printStackTrace();
            GraceException.display(ResponseType.FILE_UPLOAD_FAILED);
        }
        return null;
    }

    /**
     * 获取待下载文件的预签名URL
     * @param objectName 对象名称
     * @return 下载地址
     */
    public String getDownloadUrl(String objectName){
        GetPresignedObjectUrlArgs args = getGetPresignedObjectUrlArgs(Method.GET,objectName);
        try {
            return minioClient.getPresignedObjectUrl(args);
        }catch (Exception e){
            e.printStackTrace();
            GraceException.display(ResponseType.FILE_DOWNLOAD_FAILED);
        }
        return null;
    }

    /**
     * 获取预签名URL参数对象
     * @param method 请求方式
     * @param objectName 对象名称
     * @return 参数对象
     */
    private GetPresignedObjectUrlArgs getGetPresignedObjectUrlArgs(Method method, String objectName){
        Map<String, String> reqParams = new HashMap<>();
        reqParams.put("response-content-type", "application/json");
        return GetPresignedObjectUrlArgs.builder()
                .method(method)
                .bucket(prop.getBucketName())
                .object(objectName)
                .expiry(30, TimeUnit.MINUTES)
                .extraQueryParams(reqParams)
                .build();
    }

}